<script setup>
import { useCommunityNameList } from '@/hooks/index.js'
import { reactive, ref, computed } from 'vue';
import { addProjectAPI, editProjectAPI, getProjectInfoAPI } from '@/api/expenses';
import { ElMessage } from 'element-plus';

const communityList = useCommunityNameList()
const emit = defineEmits(['updateList'])

// 表单数据
const defaultData = {
  community_code: '',
  name: '',
}
const formData = reactive({ ...defaultData })

// 表单校验
const formRules = {
  community_code: [{ required: true, message: "请选择", trigger: "change" }],
  name: [{ required: true, message: "请输入", trigger: "blur" }],
}

// 表单引用
const formRef = ref()

// 弹框控制变量
const isShow = ref(false)

// 表单提交
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value.validate()
    // 处理数据
    const data = toRaw(formData)
    // 发送请求
    formData.id ? await editProjectAPI(data) : await addProjectAPI(data)
    // 提示成功
    ElMessage.success('操作成功')
    // 关闭弹框
    isShow.value = false
    // 移除校验
    await formRef.value.resetFields()
    // 更新列表
    emit('updateList')
  } catch (error) {
    console.log(error)
  }
}

// 关闭事件
const closeDialog = () => {
  // 移除校验
  formRef.value.resetFields()
  // 重置表单
  Object.assign(formData, { ...defaultData })
}

// 标题事件
const title = computed(() => {
  return formData.id ? '修改收费项目' : '新增收费项目'
})

// 数据回显
const replyData = async (id) => {
  let { data } = await getProjectInfoAPI(id)
  console.log(data)
  Object.assign(formData, data)
  isShow.value = true
}

defineExpose({
  isShow, replyData
})

</script>

<template>
  <el-dialog :title="title" v-model="isShow" width="45%" @close="closeDialog">
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px" :inline="false" size="normal">

      <el-form-item label="所属小区" prop="community_code">
        <el-select v-model="formData.community_code" style="width: 50%">
          <el-option v-for="item in communityList" :key="item.id" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="项目名称" prop="name">
        <el-input v-model="formData.name" style="width: 50%"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped></style>